package ${table.basePackage}.service.impl;
<#-- 引入公共函数和变量 -->
<#include "../base/service-common.ftl">
<#-- 引入 import 语句 -->
<#include "../base/service-imports.ftl">

/**
 * ${table.comment!table.entityName} - 服务实现类（一对多模式）
 * 
 * 遵循Kexio开发规范：
 * - 使用 EntityDTOConverter 进行实体和DTO转换
 * - 使用 ExcelUtils 处理导入导出
 * - 异常统一抛出，由全局异常处理器捕获
 * - 事务边界清晰，确保数据一致性
 * - 租户ID通过BaseEntity自动处理
 * - 支持主从表关联数据的保存、更新和查询
 * 
 * @author ${user.name!"系统"}
 * @since ${now?string('yyyy-MM-dd HH:mm:ss')}
 */
@Service
@Transactional(readOnly = true)
public class ${table.entityName}ServiceImpl implements ${table.entityName}Service {
    
    private static final Logger logger = LoggerFactory.getLogger(${table.entityName}ServiceImpl.class);

    @Autowired
    private ${table.entityName}Mapper ${lowerEntity}Mapper;

    // TODO: 注入子表Mapper
<#if table.ext?? && table.ext.relations??>
  <#list table.ext.relations as r>
    // @Autowired
    // private ${r.entityClass}Mapper ${r.alias}Mapper;
  </#list>
</#if>

<#-- 引入分页查询和列表查询方法（这两个不需要加载关联数据） -->
    @Override
    public PageResponse<${table.entityName}DTO> queryPage(${table.entityName}DTO queryDTO) {
        // 规范化分页参数
        PageUtils.normalizePage(queryDTO);
        
        // 构建查询条件
        LambdaQueryWrapper<${table.entityName}> wrapper = buildQueryWrapper(queryDTO);
        
        // 分页查询
        Page<${table.entityName}> page = new Page<>(queryDTO.getCurrent(), queryDTO.getPageSize());
        ${lowerEntity}Mapper.selectPage(page, wrapper);
        
        // 转换为DTO并返回（不加载关联数据，性能考虑）
        return PageConverters.convertWithMapping(page, 
            entity -> EntityDTOConverter.toDTO(entity, ${table.entityName}DTO.class));
    }

<#-- 引入覆盖的 getDetail 方法（加载关联数据） -->
<#include "../base/service-multi-getdetail.ftl">

    @Override
    public List<${table.entityName}DTO> queryList(${table.entityName}DTO queryDTO) {
        LambdaQueryWrapper<${table.entityName}> wrapper = buildQueryWrapper(queryDTO);
        List<${table.entityName}> entities = ${lowerEntity}Mapper.selectList(wrapper);
        
        // 列表查询不加载关联数据（性能考虑）
        return entities.stream()
            .map(entity -> EntityDTOConverter.toDTO(entity, ${table.entityName}DTO.class))
            .collect(Collectors.toList());
    }

<#-- 引入标准 create/update/delete 方法 -->
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ${table.entityName}DTO create(${table.entityName}DTO dto) {
        // 转换为实体
        ${table.entityName} entity = EntityDTOConverter.toEntity(dto, ${table.entityName}.class);
        
        // 插入数据库
        ${lowerEntity}Mapper.insert(entity);
        
        // 返回DTO
        return EntityDTOConverter.toDTO(entity, ${table.entityName}DTO.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ${table.entityName}DTO update(${pkType} id, ${table.entityName}DTO dto) {
        if (id == null) {
            throw BusinessException.badRequest("ID不能为空");
        }
        
        // 检查是否存在
        ${table.entityName} existing = ${lowerEntity}Mapper.selectById(id);
        if (existing == null) {
            throw BusinessException.resourceNotFound("${table.comment!table.entityName}不存在");
        }
        
        // 只更新非null字段（防止覆盖未修改的字段）
        EntityDTOConverter.updateEntity(dto, existing);
        
        // 更新数据库
        ${lowerEntity}Mapper.updateById(existing);
        
        // 返回DTO
        return EntityDTOConverter.toDTO(existing, ${table.entityName}DTO.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(${pkType} id) {
        if (id == null) {
            throw BusinessException.badRequest("ID不能为空");
        }
        
        ${table.entityName} existing = ${lowerEntity}Mapper.selectById(id);
        if (existing == null) {
            throw BusinessException.resourceNotFound("${table.comment!table.entityName}不存在");
        }
        
        ${lowerEntity}Mapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(List<${pkType}> ids) {
        if (ids == null || ids.isEmpty()) {
            throw BusinessException.badRequest("ID列表不能为空");
        }
        
        ${lowerEntity}Mapper.deleteBatchIds(ids);
    }

<#-- 引入一对多专用方法 -->
<#include "../base/service-multi-methods.ftl">

<#-- 引入 Excel 导入导出方法 -->
<#include "../base/service-excel-methods.ftl">

<#-- 引入查询条件构建方法 -->
<#include "../base/service-query-wrapper.ftl">
}

